package com.kuang.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Subject：用户
 * SecurityManager：管理所有用户
 * Realm：连接数据
 */
@Configuration
public class ShiroConfig {

    //ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("webSecurityManager") DefaultWebSecurityManager webSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(webSecurityManager);


        //添加shiro的内置拦截器
        /**
         * anon：无需认证就能访问
         * authc：必须认证才能访问
         * user：必须拥有'记住我'功能才能访问
         * perms：拥有某个资源的权限才能访问
         * role：拥有某个角色权限才能访问
         */

        Map<String, String> filterMap = new LinkedHashMap<>();

        //授权
//      filterMap.put("/user/toAdd","authc");
//      filterMap.put("/user/toUpdate","authc");

        //资源权限
        filterMap.put("/user/toAdd","perms[user:add]");
        filterMap.put("/user/toUpdate", "perms[user:update]");

        //授权
        filterMap.put("/user/*", "authc");


        bean.setFilterChainDefinitionMap(filterMap);

        //设置登录的请求
        bean.setLoginUrl("/toLogin");

        //设置未授权的请求
        bean.setUnauthorizedUrl("/noAuth");

        return bean;
    }

    //DefaultWebSecurityManager
    @Bean(name = "webSecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager webSecurityManager = new DefaultWebSecurityManager();
        webSecurityManager.setRealm(userRealm);
        return webSecurityManager;
    }

    //创建realm对象 需要自定义
    @Bean
    public UserRealm userRealm() {
        return new UserRealm();
    }


    //ShiroDialect  shiro整合thymeleaf
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }


}
